package com.bodacn.keypoint;


import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.media.MediaPlayer;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import androidx.fragment.app.Fragment;
import android.text.InputType;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.net.HttpURLConnection;
import java.net.URL;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.ReentrantLock;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static android.view.ViewGroup.LayoutParams.MATCH_PARENT;


/**
 * A simple {@link Fragment} subclass.
 */
public class FragmentE extends Fragment implements View.OnClickListener {
    public static String TAG=FragmentE.class.getName();
    public static final int msgFocusBarcode = 1001;
    public static final int msgGetImg = 1002;
    public static final int msgShowImage =1003;
    public static final int msgGreenLight = 2001;
    public static final int msgRedLight = 2002;
    public static final int msgGrayLight = 2003;
    public static final int MSG_SCANBARCODE = 9001;
    public static final int MSG_DETAIL = 9002;
    public static final int MSG_PROCRESULT=9004;
    public static final int MSG_GETPLACE=9005;
    public static final int MSG_GETPATH=9006;
    public static final int MSG_PUTNEXT=9007;
    public static final int MSG_AGVREC=9008;
    ReentrantLock reentrantLock = new ReentrantLock();

    //用于将Activity中的参数传给Fragment
    private Map<String,Object> fragmentParams=new HashMap<String,Object>();
    //用于与主Activity通讯;
    private Handler mainHandler;
    //全局变量
    Toast curToast;
    String curLoginUserNo,curLoginUser,curServiceUrl="",curServiceDir="",curDepartNo,curDepart,CPUID;
    Button btn_find,btn_Query,btn_Call;
    ImageButton btn_editBarcode;
    ListView detailListView;
    TextView txt_HintInfo,txt_OrderNo,txt_StyleNo,txt_StyleSort,txt_PO,txt_Color,txt_PackNo,txt_Size,txt_ReadyScan,txt_OwenScan,txt_Number,txt_TargetNum,txt_TodaySewNum;
    TextView tv_runState;
    EditText edt_barcode;
    CheckBox chk_Repeat;
    static Drawable drawable_gray,drawable_green,drawable_red;
    String curImageFileName ="",curStyleID="";
    ImageView imgv_StlyleImage;
    JSONArray detailJSON,queryJSON,procRstJSON, headJSON,placeJSON,resultJSON,pathJSON;
    LinearLayout templetlisthead;
    ListView selectTempletList;
    String selLinePlace="",selHousePlace="";
    Integer curAgvReqIndex=0;
    String AgvServerURL="http://192.168.10.26/cms/services/rest/hikRpcService/";
    private ProgressDialog waitDialog = null;
    //主程序回调传参--------------------------------------------开始;
    private FragmentECallBack mFragmentECallBack;
    /*定义一个业务接口,主程序负责实现，所以需在主程序implements中加上这个接口的引用>>>>>切记<<<<<<
    该Fragment所在Activity需要实现该接口
    该Fragment将通过此接口与它所在的Activity交互*/
    public interface FragmentECallBack {
        // 里面传个值@param Map<String,Object>适应多种类型;
        void FragmentEWorkAndTransParams(Map<String, Object> Params);
    }
    //主程序回调传参--------------------------------------------结束;
    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        Activity activity = (Activity) context;
        if (!(activity instanceof FragmentECallBack)) {
            throw new IllegalStateException("MainActivity必须实现FragmentECallBack接口");
        }
        mFragmentECallBack=(FragmentECallBack) activity;
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mFragmentECallBack=null;
    }

    //判断是否为数字，不然不转
    public static boolean isNumer(String str) {
        Pattern pattern = Pattern.compile("-?[0-9]+\\.?[0-9]+");
        Matcher isNum = pattern.matcher(str);
        if (!isNum.matches()) {
            return false;
        }
        return true;
    }

    public FragmentE() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //得到Activity的Handler,用于发消息给主Activity;
        MainActivity activity=(MainActivity) getActivity();
        mainHandler=activity.mainHandler;
        //加接口监听
        activity.setTransParamsListenerE(new MainActivity.OnTransParamsListenerE() {
            @Override
            public void TransParams(Map<String, Object> mParams) {
                if (mParams!=null) {
                    try {
                        String paramComm= mParams.get("ParamComm").toString();
                        if (paramComm=="LoginParam")
                        {
                            Log.d(this.getClass().getName(),"LoginParam------------------>1");
                            System.out.println(mParams);
                            //传递登陆参数信息;
                            curLoginUserNo=mParams.get("LoginUserNo").toString();
                            curLoginUser=mParams.get("LoginUser").toString();
                            curServiceUrl=mParams.get("ServiceUrl").toString();
                            curServiceDir=mParams.get("ServiceDir").toString();
                            curDepartNo=mParams.get("DepartNo").toString();
                            curDepart=mParams.get("Depart").toString();
                            CPUID=mParams.get("CPUID").toString();
                            Log.d(this.getClass().getName(),"LoginParam------------------>2");
                            //发消息置焦点
                            Message msg =new Message();
                            msg.what = msgFocusBarcode;
                            fragmentHandler.removeMessages(msg.what);
                            fragmentHandler.sendMessage(msg);
                        }
                        if (paramComm=="LightParam")
                        {
                            //Log.d(this.getClass().getName(),"LightParam------------------>1");
                            //传递登陆参数信息;
                            String ConColor=mParams.get("Color").toString();
                            //发消息置焦点
                            Message msg =new Message();
                            if (ConColor=="Green") msg.what = msgGreenLight;
                            if (ConColor=="Red") msg.what = msgRedLight;
                            if (ConColor=="Gray") msg.what = msgGrayLight;
                            fragmentHandler.removeMessages(msgGreenLight);
                            fragmentHandler.removeMessages(msgRedLight);
                            fragmentHandler.removeMessages(msgGrayLight);
                            fragmentHandler.sendMessage(msg);
                        }
                        if ((paramComm=="Barcode")){
                            String barcode=mParams.get("Barcode").toString();
                            edt_barcode.setText(barcode);
                            searchBarcodeData(barcode,txt_OrderNo.getText().toString(),txt_StyleNo.getText().toString());
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        });
    }



    /**
     * 定义一个Handler用于接收Fragment发出来的指令
     */
    public Handler fragmentHandler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if(msg!=null){
                int msgId = msg.what;
                switch (msgId) {
                    case msgGreenLight:
                        tv_runState.setBackground(drawable_green);
                        tv_runState.refreshDrawableState();
                        try {
                            Thread.sleep(200);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        break;
                    case msgRedLight:
                        tv_runState.setBackground(drawable_red);
                        tv_runState.refreshDrawableState();
                        try {
                            Thread.sleep(200);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        break;
                    case msgGrayLight:
                        tv_runState.setBackground(drawable_gray);
                        tv_runState.refreshDrawableState();
                        try {
                            Thread.sleep(200);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        break;

                    case msgGetImg:
                        //设置焦点
                        System.out.println(TAG+"获取图片-------------------------------1.Start");
                        if (curImageFileName.length()>0)
                            getImage(curStyleID,txt_StyleNo.getText().toString(),txt_StyleSort.getText().toString());
                        System.out.println(TAG+"获取图片-------------------------------1.End");
                        break;
                    case msgShowImage:
                        //判断本地是否有图片;
                        String imgfilepath = getActivity().getCacheDir().toString();
                        File file = new File(imgfilepath + "/" + curImageFileName);
                        //判断图片是否存在，如果不存在则从网络获取;
                        if (file.exists() == true) {
                            Log.d(TAG, "准备从本地取图片显示---------------");
                            //从本地取图片
                            Bitmap bitmap = getLoacalBitmap(imgfilepath + "/" + curImageFileName);
                            imgv_StlyleImage.setImageBitmap(bitmap);
                        }
                        break;
                    case msgFocusBarcode:
                        //任意消息来均置焦点
                        if (edt_barcode.isFocused()==false) setEditBarcodeFocus();
                        break;
                    case MSG_SCANBARCODE:
                        fillFormtext();
                        break;
                    case MSG_DETAIL:
                        //显示预排单;
                        final DetailListAdapter detailListAdapter = new DetailListAdapter(getActivity());
                        detailListView.setAdapter(detailListAdapter);
                        break;
                    case MSG_PROCRESULT:
                        String resultMsg = null;
                        try {
                            resultMsg = procRstJSON.optJSONObject(0).getString("PROCRESULT");
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        //提示提交完成，需确认;
                        // 创建对话框
                        AlertDialog alertDialog = new AlertDialog.Builder(getActivity())
                                .setTitle(getString(R.string.SystemHint)).setMessage(resultMsg)
                                .setPositiveButton(getString(R.string.Affirm), new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int which) {
                                        hideBottomUIMenu();
                                    }
                                }).create();
                        alertDialog.show(); // 显示对话框
                        break;
                    case MSG_GETPLACE:
                        showSelectPlace();
                        break;
                    case MSG_GETPATH:
                        if (pathJSON!=null){
                            if (pathJSON.length()>0){
                                if (pathJSON.optJSONObject(0).has("ReqCode")&&pathJSON.optJSONObject(0).has("StartPlace")&&pathJSON.optJSONObject(0).has("EndPlace")){
                                    curAgvReqIndex=0;
                                    try {
                                        PutAGVTask(pathJSON.optJSONObject(curAgvReqIndex).getString("ReqCode"),
                                                pathJSON.optJSONObject(curAgvReqIndex).getString("StartPlace"),
                                                pathJSON.optJSONObject(curAgvReqIndex).getString("EndPlace"));
                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }
                                }
                            }
                        }
                        break;
                    case MSG_AGVREC:
                        //可以通过回调成功来继续后面任务;
                    case MSG_PUTNEXT:
                        if (curAgvReqIndex<pathJSON.length()-1){
                            curAgvReqIndex++;
                            try {
                                PutAGVTask(pathJSON.optJSONObject(curAgvReqIndex).getString("ReqCode"),
                                        pathJSON.optJSONObject(curAgvReqIndex).getString("StartPlace"),
                                        pathJSON.optJSONObject(curAgvReqIndex).getString("EndPlace"));
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                        break;
                    default:
                        break;
                }
            }
        }
    };

    private void PutAGVTask(String paramReqCode,String paramStartPlace,String paramEndPlace){
        try {
            JSONArray positionCodePath=new JSONArray("[]");
            JSONObject codePath = new JSONObject();
            codePath.put("positionCode",paramStartPlace);
            codePath.put("type","00");
            positionCodePath.put(codePath);
            codePath = new JSONObject();
            codePath.put("positionCode",paramEndPlace);
            codePath.put("type","00");
            positionCodePath.put(codePath);
            JSONObject jsonParam = new JSONObject();
            jsonParam.put("reqCode", paramReqCode);
            jsonParam.put("reqTime", "");
            jsonParam.put("tokenCode", "");
            jsonParam.put("interfaceName", "genAgvSchedulingTask");
            jsonParam.put("taskTyp", "F01");
            jsonParam.put("wbCode", "");
            jsonParam.put("positionCodePath", positionCodePath);
            jsonParam.put("podCode", "");
            jsonParam.put("podDir", "");
            jsonParam.put("priority", "");
            jsonParam.put("agvCode", "");
            jsonParam.put("taskCode", "");
            jsonParam.put("data", "");
            System.out.println(jsonParam);
            //提交参数;
            sendJsonPost(AgvServerURL,"genAgvSchedulingTask",jsonParam.toString());
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    public void sendJsonPost(String serviceUrl, String methodName, String Json) {
        //组织参数传到匿名类中;
        Map<String,Object> params=new HashMap<String,Object>();
        params.put("serviceUrl",serviceUrl);
        params.put("methodName",methodName);
        params.put("Json",Json);
        //创建匿名类用于WebService调用;
        new AsyncTask<Map<String,Object>,Void,String>()
        {
            @Override
            protected String doInBackground(Map<String, Object>... params) {
                String serviceUrl= (String) params[0].get("serviceUrl");
                System.out.println(serviceUrl);
                String methodName= (String) params[0].get("methodName");
                String Json= (String) params[0].get("Json");
                // HttpClient 6.0被抛弃了
                String result = null;
                BufferedReader reader = null;
                try {
                    System.out.println("sendCancelJsonPost:"+methodName);
                    String urlPath = serviceUrl + methodName;
                    Log.e("sendCancelJsonPost",urlPath);
                    URL url = new URL(urlPath);
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    conn.setRequestMethod("POST");
                    conn.setDoOutput(true);
                    conn.setDoInput(true);
                    conn.setUseCaches(false);
                    conn.setRequestProperty("Connection", "Keep-Alive");
                    conn.setRequestProperty("Charset", "UTF-8");
                    conn.setRequestProperty("User-Agent","");
                    // 设置文件类型:
                    conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
                    // 设置接收类型否则返回415错误
                    //conn.setRequestProperty("accept","*/*")此处为暴力方法设置接受所有类型，以此来防范返回415;
                    conn.setRequestProperty("accept", "application/json");
                    // 往服务器里面发送数据
                    if (Json != null && !TextUtils.isEmpty(Json)) {
                        byte[] writebytes = Json.getBytes();
                        // 设置文件长度
                        conn.setRequestProperty("Content-Length", String.valueOf(writebytes.length));
                        OutputStream outwritestream = conn.getOutputStream();
                        outwritestream.write(Json.getBytes());
                        outwritestream.flush();
                        outwritestream.close();
                        Log.d("hlhupload", "doJsonPost: conn-----" + conn.getResponseCode());
                    }
                    if (conn.getResponseCode() == 200) {
                        reader = new BufferedReader(
                                new InputStreamReader(conn.getInputStream()));
                        result = reader.readLine();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (reader != null) {
                        try {
                            reader.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
                System.out.println(result);
                return result;
            }

            @Override
            protected void onPostExecute(String s) {
                super.onPostExecute(s);
                if (s==null) {
                    txt_HintInfo.setText("调用失败!");
                    return;
                }
                //这部分主要用于UI更新;
                System.out.println("onPostExecute:"+s);
                try {
                    JSONObject jsonObject = new JSONObject(s);
                    if (jsonObject.has("data")&&jsonObject.has("message")&&jsonObject.has("reqCode")){
                        if (jsonObject.getString("message").equals("成功")) {
                            //调用任务成功回调;
                            AGVRecOK(jsonObject.getString("reqCode"), jsonObject.getString("data"));
                            //最后一条命令则给上调用成功;
                            if (pathJSON!=null) {
                                if (curAgvReqIndex == pathJSON.length() - 1)
                                    txt_HintInfo.setText("AGV调度指令发送成功!");
                                else txt_HintInfo.setText("AGV调度准备发送第" + curAgvReqIndex + '条');
                            }
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        }.execute(params);

    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View root = inflater.inflate(R.layout.fragment_e, container, false);
        initView(root);
        System.out.println(this.getClass().getName()+"_onCreateView");
        return root;
    }


    private void initView(View view) {
        detailListView=(ListView) view.findViewById(R.id.detailListView);
        detailListView.setFocusableInTouchMode(false);
        detailListView.setFocusable(false);
        btn_Call=view.findViewById(R.id.btn_Call);
        btn_Call.setOnClickListener(this);
        btn_find=(Button)view.findViewById(R.id.btn_find);
        btn_find.setOnClickListener(this);
        btn_Query=(Button)view.findViewById(R.id.btn_Query);
        btn_Query.setOnClickListener(this);
        btn_editBarcode=(ImageButton)view.findViewById(R.id.btn_editBarcode);
        btn_editBarcode.setOnClickListener(this);
        btn_editBarcode.setFocusable(false);
        btn_editBarcode.setFocusableInTouchMode(false);
        imgv_StlyleImage = view.findViewById(R.id.imgv_StyleImage);
        imgv_StlyleImage.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                //删除CacheDir文件
                deleteFilesByDirectory(getActivity().getCacheDir());
                curToast.setText("缓存文件已被清空!");
                curToast.show();
                return false;
            }
        });
        //运行状态;
        chk_Repeat=view.findViewById(R.id.chk_Repeat);
        chk_Repeat.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                //传消息给主界面;
                if (mFragmentECallBack!=null)
                {
                    fragmentParams.clear();
                    fragmentParams.put("ParamComm","Repeat");//命令;
                    if (isChecked==true) fragmentParams.put("ParamValue","T");//参数;
                    else fragmentParams.put("ParamValue","F");//参数;
                    mFragmentECallBack.FragmentEWorkAndTransParams(fragmentParams);
                } else Log.d("msg","mFragmentECallBack-----------空的咋办");
            }
        });
        tv_runState=view.findViewById(R.id.tv_runState);
        //状态背景颜色
        drawable_gray = getResources().getDrawable(R.drawable.round_gray_background);
        drawable_green = getResources().getDrawable(R.drawable.round_green_background);
        drawable_red = getResources().getDrawable(R.drawable.round_red_background);
        //界面Edit;
        edt_barcode=(EditText)view.findViewById(R.id.edt_barcode);
        edt_barcode.setInputType(InputType.TYPE_NULL);
        edt_barcode.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (event!=null){
                    if ((event.getAction()==KeyEvent.ACTION_DOWN)&&(event.getKeyCode()== KeyEvent.KEYCODE_ENTER))
                    {
                        //虚拟键盘或实体键盘可考虑是否通过deviceID，或source来判断
                        // KeyEvent:KeyEvent { action=ACTION_DOWN, keyCode=KEYCODE_ENTER, scanCode=0, metaState=0, flags=0x16, repeatCount=0, eventTime=142515176, downTime=142515176, deviceId=-1, source=0x0 }
                        //隐藏键盘
                        hideIM(v);
                        if (edt_barcode.getText().length()==0) {
                            curToast.setText(getString(R.string.PleaseInputBarcode));
                            curToast.show();
                        }
                        //执行查询;
                        searchBarcodeData(edt_barcode.getText().toString(),txt_OrderNo.getText().toString(),txt_StyleNo.getText().toString());
                        //未有焦点
                        if (edt_barcode.isFocused()==false){
                            //发消息置焦点
                            Message msg =new Message();
                            msg.what = msgFocusBarcode;
                            fragmentHandler.removeMessages(msg.what);
                            fragmentHandler.sendMessage(msg);
                        } else edt_barcode.selectAll();
                    }

                }
                return false;
            }
        });
        edt_barcode.requestFocus();
        edt_barcode.requestFocusFromTouch();
        txt_HintInfo=view.findViewById(R.id.txt_HintInfo);
        txt_OrderNo=view.findViewById(R.id.txt_OrderNo);
        txt_StyleNo=view.findViewById(R.id.txt_StyleNo);
        txt_PO=view.findViewById(R.id.txt_PO);
        txt_Color=view.findViewById(R.id.txt_Color);
        txt_PackNo=view.findViewById(R.id.txt_PackNo);
        txt_Size=view.findViewById(R.id.txt_Size);
        txt_ReadyScan=view.findViewById(R.id.txt_ReadyScan);
        txt_OwenScan=view.findViewById(R.id.txt_OwenScan);
        txt_Number=view.findViewById(R.id.txt_QCNumber);
        txt_TargetNum=view.findViewById(R.id.txt_TargetNum);
        txt_TodaySewNum=view.findViewById(R.id.txt_TodaySewNum);
        txt_StyleSort=view.findViewById(R.id.txt_StyleSort);

        //初始提醒;
        curToast = Toast.makeText(getActivity(), "", Toast.LENGTH_SHORT);
        //提示框pd=new ProgressDialog(this);
        waitDialog = new ProgressDialog(getActivity());
        waitDialog.setTitle(getString(R.string.SystemHint));
    }


    //显示工序选择
    private void showSelectPlace(){
        if (placeJSON==null) {
            curToast.setText("没有位置信息,不能呼叫!");
            curToast.show();
            return;
        }
        try {
            headJSON=new JSONArray("[{\"TitleName\":\"Depart\",\"TitleText\":\"流水线\",\"TxtSize\":18,\"TxtWidth\":100,\"AutoZoom\":1,\"Align\":0,\"Color\":\"Blue\"}," +
                    "{\"TitleName\":\"LinePlace\",\"TitleText\":\"产线位置\",\"TxtSize\":18,\"TxtWidth\":100,\"AutoZoom\":1,\"Align\":0,\"Color\":\"Blue\"},"+
                    "{\"TitleName\":\"LineState\",\"TitleText\":\"状态\",\"TxtSize\":18,\"TxtWidth\":80,\"AutoZoom\":1,\"Align\":0,\"Color\":\"Blue\"},"+
                    "{\"TitleName\":\"HousePlace\",\"TitleText\":\"库存位置\",\"TxtSize\":18,\"TxtWidth\":100,\"AutoZoom\":1,\"Align\":0,\"Color\":\"Blue\"},"+
                    "{\"TitleName\":\"OrderInfo\",\"TitleText\":\"制单信息\",\"TxtSize\":18,\"TxtWidth\":250,\"AutoZoom\":1,\"Align\":0,\"Color\":\"Blue\"},"+
                    "{\"TitleName\":\"HouseState\",\"TitleText\":\"状态\",\"TxtSize\":18,\"TxtWidth\":80,\"AutoZoom\":1,\"Align\":0,\"Color\":\"Blue\"},"+
                    "{\"TitleName\":\"Recommend\",\"TitleText\":\"推荐\",\"TxtSize\":18,\"TxtWidth\":80,\"AutoZoom\":1,\"Align\":0,\"Color\":\"Blue\"}]");


        } catch (JSONException e) {
            e.printStackTrace();
        }
        //创建布局
        String dgCaption="呼叫列表选择";
        LayoutInflater inflater=this.getLayoutInflater();
        final View selectTemplet=inflater.inflate(R.layout.select_templet, null);
        templetlisthead=selectTemplet.findViewById(R.id.templetlisthead);
        //创建表头;
        CreateListHead();
        detailJSON=placeJSON;
        //Activity.findViewById最终还是会调用View.findViewById
        selectTempletList=selectTemplet.findViewById(R.id.selectTempletList);
        selectTempletList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                try {
                    view.setSelected(true);
                    if (detailJSON.optJSONObject(position).has("LinePlace")==true)
                        selLinePlace=detailJSON.optJSONObject(position).getString("LinePlace");
                    if (detailJSON.optJSONObject(position).has("HousePlace")==true)
                        selHousePlace=detailJSON.optJSONObject(position).getString("HousePlace");
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
        //显示表明细
        SelectTempletListAdapter selectTempletListAdapter=new SelectTempletListAdapter(getContext());
        selectTempletList.setAdapter(selectTempletListAdapter);
        //创建对话框
        AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
        builder.setView(selectTemplet).setPositiveButton("确定", new DialogInterface.OnClickListener(){
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Field field = null;
                        if (selLinePlace.length() == 0) {
                            try {
                                field = dialog.getClass().getSuperclass().getDeclaredField("mShowing");
                                field.setAccessible(true);
                                field.set(dialog, false);
                            } catch (NoSuchFieldException e) {
                                e.printStackTrace();
                            } catch (IllegalAccessException e) {
                                e.printStackTrace();
                            }
                            curToast.setText("请点击要选择的内容！");
                            curToast.show();
                        } else{
                            txt_HintInfo.setText("获取AGV路径.....");
                            GetCallPath(selLinePlace,selHousePlace);
                            try {
                                field = dialog.getClass().getSuperclass().getDeclaredField("mShowing");
                                field.setAccessible(true);
                                field.set(dialog, true);
                            } catch (NoSuchFieldException e) {
                                e.printStackTrace();
                            } catch (IllegalAccessException e) {
                                e.printStackTrace();
                            }
                        }
                    }

                }
        ).setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                try {
                    selLinePlace="";
                    selHousePlace="";
                    txt_HintInfo.setText("");
                    Field field = null;
                    field = dialog.getClass().getSuperclass().getDeclaredField( "mShowing" );
                    field.setAccessible(true );
                    field.set(dialog,true );
                } catch (NoSuchFieldException e) {
                    e.printStackTrace();
                }
                catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
                Log.v("tag","取消");
            }
        }).setTitle(dgCaption);
        final AlertDialog alterDialog =builder.create();
        alterDialog.setOnShowListener(new DialogInterface.OnShowListener() {
            @Override
            public void onShow(DialogInterface dialog) {
                //禁止两个按键上获取焦点，不然扫描框里就会失去焦点,在OnShow之前;
                System.out.println("alterDialog-setOnShowListener");
            }
        });
        alterDialog.show();
        //此处设置位置窗体大小
        WindowManager.LayoutParams params = alterDialog.getWindow().getAttributes();
        params.width =850;
        params.height = 600 ;
        alterDialog.getWindow().setAttributes(params);
    }

    //呼叫AGV
    private void GetCallPath(String paramLinePlace, String paramHousePlace) {
        //调用过程获取路径
        System.out.println("getDepartment------------------------------------->");
        try {
            pathJSON=new JSONArray("[]");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        //执行SQL过程
        String SqlComm = "Exec KeyPoint_AGV_GetPath @OPERTYPE='GETPATH',@LinePlace='"+paramLinePlace+"',@HousePlace='"+paramHousePlace+"',@DepartNo='"+curDepartNo+"',@UserNo='"+curLoginUserNo+ "',@CPUID='"+CPUID+"'";
        ReadSQLData(SqlComm);
    }
    //呼叫AGV
    private void AGVRecOK(String paramReqCode, String paramTaskCode) {
        //调用过程获取路径
        System.out.println("getDepartment------------------------------------->");
        try {
            pathJSON=new JSONArray("[]");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        //执行SQL过程
        String SqlComm = "Exec KeyPoint_AGV_CallBack @OPERTYPE='AGVREC',@ReqCode='"+paramReqCode+"',@TaskCode='"+paramTaskCode+"',@DepartNo='"+curDepartNo+"',@UserNo='"+curLoginUserNo+ "',@CPUID='"+CPUID+"'";
        ReadSQLData(SqlComm);
    }

    //数据适配器，继承自BaseAdapter;
    private final class SelectTempletListAdapter extends BaseAdapter {
        private LayoutInflater inflater;
        public SelectTempletListAdapter(Context context) {
            inflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }
        public  String TrnasValue(String params)
        {
            if ((params.toUpperCase()=="NULL".toUpperCase())||(params=="0")||(params=="0.0"))
                return "";
            else return params;
        }
        @Override
        public int getCount() {
            //每页行数
            return detailJSON.length();
        }
        @Override
        public Object getItem(int position) {
            try {
                if (position<detailJSON.length())
                    return detailJSON.getJSONArray(position);
                else
                    return null;
            } catch (JSONException e)
            {
                e.printStackTrace();
                System.out.println("getItem取JSON数据出错!");
                return  null;
            }
        }
        @Override
        public long getItemId(int position) {
            return position;
        }
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View view = inflater.inflate(R.layout.select_templet_item, null, false);
            //变换背景色
            /*
            if (position%2==1) {
                view.setBackgroundColor(getResources().getColor(R.color.content));
            }
            */
            int pullVatListWidth=parent.getWidth();
            view.setLayoutParams(new ListView.LayoutParams(pullVatListWidth,60));
            //转换分页码;
            int curPosition= position;
            String tmpValue;
            int color = getResources().getColor(R.color.text_black);
            if (curPosition<detailJSON.length()) {
                try {
                    Log.d(TAG, "getView()----------------------------------------------------->" + position);
                    if (detailJSON.optJSONObject(curPosition).has("ConColor") == true) {
                        tmpValue = detailJSON.optJSONObject(curPosition).getString("ConColor");
                        color=GetColorValue(tmpValue);
                    }
                    for (int i = 0; i < headJSON.length(); i++)
                        if (headJSON.optJSONObject(i).has("TitleText") == true) {
                            try {
                                String TitleName = headJSON.optJSONObject(i).getString("TitleName");
                                if (detailJSON.optJSONObject(curPosition).has(TitleName)==true) tmpValue= detailJSON.optJSONObject(curPosition).getString(TitleName);
                                else tmpValue="unReturn";
                                int TxtSize = headJSON.optJSONObject(i).getInt("TxtSize");
                                float txtWidth = headJSON.optJSONObject(i).getLong("TxtWidth");
                                int AutoZoom = headJSON.optJSONObject(i).getInt("AutoZoom");
                                TextView tv = new TextView(view.getContext());
                                tv.setText(TrnasValue(tmpValue));
                                tv.setWidth((int) txtWidth);
                                tv.setTextColor(color);
                                tv.setGravity(Gravity.CENTER_VERTICAL);
                                if (headJSON.optJSONObject(i).has("Align")==true) {
                                    int Align;
                                    Align = headJSON.optJSONObject(i).getInt("Align");
                                    switch (Align) {
                                        case 0:
                                            tv.setGravity(Gravity.CENTER_VERTICAL | Gravity.LEFT);
                                            break;
                                        case 1:
                                            tv.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL);
                                            break;
                                        case 2:
                                            tv.setGravity(Gravity.CENTER_VERTICAL | Gravity.RIGHT);
                                            break;
                                        default:
                                            tv.setGravity(Gravity.CENTER_VERTICAL);
                                            break;
                                    }
                                }
                                tv.setTextSize(TxtSize);
                                //添加到View中;
                                if (AutoZoom == 1)
                                    ((LinearLayout)view).addView(tv, new LinearLayout.LayoutParams((int) txtWidth, MATCH_PARENT, 1));
                                else ((LinearLayout)view).addView(tv);
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                } catch (JSONException e) {
                    e.printStackTrace();
                    Toast.makeText(getContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
                }
            }
            return view;
        }
    }


    //从字符串转颜色
    //从字符串转颜色
    private int GetColorValue(String paramColor){
        int PenColor= Color.WHITE;
        String StrPenColor=paramColor;
        if ((StrPenColor.indexOf("#")==0)&&(StrPenColor.length()==7)){
            int testColor=Integer.parseInt(StrPenColor.substring(1),16);
            int red = (testColor & 0xff0000) >> 16;
            int green = (testColor & 0x00ff00) >> 8;
            int blue = (testColor & 0x0000ff);
            PenColor=Color.rgb(red, green, blue);
        }else {
            if (isNumer(StrPenColor)) {
                int testColor = Integer.parseInt(StrPenColor);
                int red = (testColor & 0xff0000) >> 16;
                int green = (testColor & 0x00ff00) >> 8;
                int blue = (testColor & 0x0000ff);
                PenColor = Color.rgb(red, green, blue);
            } else {
                if (StrPenColor.equals("Black") == true)
                    PenColor = Color.BLACK;
                if (StrPenColor.equals("Blue") == true)
                    PenColor = Color.BLUE;
                if (StrPenColor.equals("Yellow") == true)
                    PenColor = Color.YELLOW;
                if (StrPenColor.equals("Red") == true)
                    PenColor = Color.RED;
                if (StrPenColor.equals("Green") == true)
                    PenColor = Color.GREEN;
                if (StrPenColor.equals("Gray") == true)
                    PenColor = Color.LTGRAY;
                if (StrPenColor.equals("White") == true)
                    PenColor = Color.WHITE;
            }
        }
        return PenColor;
    }

    //创建列;
    private void CreateListHead() {
        //内容为表头，宽度，自适应;
        if ((headJSON != null) && (headJSON.length() > 0)) {
            int childCount = templetlisthead.getChildCount();
            for (int i = childCount - 1; i >= 0; i--) {
                View view = templetlisthead.getChildAt(i);
                if (view instanceof TextView) {
                    templetlisthead.removeViewAt(i);
                }
            }
            //创建列
            String TitleText,TitleName;
            float  txtWidth;
            int TxtSize,AutoZoom,Align;
            for (int i=0;i<headJSON.length();i++)
                if (headJSON.optJSONObject(i).has("TitleText") == true) {
                    try {
                        TitleName = headJSON.optJSONObject(i).getString("TitleName");
                        TitleText = headJSON.optJSONObject(i).getString("TitleText");
                        TxtSize = headJSON.optJSONObject(i).getInt("TxtSize");
                        txtWidth = headJSON.optJSONObject(i).getLong("TxtWidth");
                        AutoZoom = headJSON.optJSONObject(i).getInt("AutoZoom");
                        TextView tv = new TextView(getContext());
                        tv.setText(TitleText);
                        tv.setWidth((int) txtWidth);
                        tv.setTextColor(getResources().getColor(R.color.white));
                        tv.setTextSize(TxtSize);
                        if (headJSON.optJSONObject(i).has("Align")==true) {
                            Align = headJSON.optJSONObject(i).getInt("Align");
                            switch (Align) {
                                case 0:
                                    tv.setGravity(Gravity.CENTER_VERTICAL | Gravity.LEFT);
                                    break;
                                case 1:
                                    tv.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL);
                                    break;
                                case 2:
                                    tv.setGravity(Gravity.CENTER_VERTICAL | Gravity.RIGHT);
                                    break;
                                default:
                                    tv.setGravity(Gravity.CENTER_VERTICAL);
                                    break;
                            }
                        }
                        //自定义文字颜色;
                        if (headJSON.optJSONObject(i).has("Color")==true){
                            tv.setTextColor(GetColorValue( headJSON.optJSONObject(i).getString("Color")));
                        }
                        //添加到View中;
                        if (AutoZoom==1) templetlisthead.addView(tv,new LinearLayout.LayoutParams((int) txtWidth, MATCH_PARENT, 1));
                        else templetlisthead.addView(tv);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            templetlisthead.postInvalidate();
        }
    }
    //插放音乐;
    private void playRingtone(){
        Uri notification = Uri.parse("android.resource://"+getActivity().getPackageName()+"/"+R.raw.scan);
        Ringtone r = RingtoneManager.getRingtone(getActivity(), notification);
        r.play();

    }
    //刷新缸布列表;
    private void searchBarcodeData(String BarcodeParam,String OrderNoParam,String StyleNoParam)
    {
        playRingtone();
        //指示灯颜色为红色
        tv_runState.setBackground(drawable_red);
        //传消息给主界面;
        if (mFragmentECallBack!=null)
        {
            fragmentParams.clear();
            fragmentParams.put("ParamComm","CardNo");//命令;
            if (BarcodeParam.indexOf("#")==0) BarcodeParam=BarcodeParam.substring(1);
            if (BarcodeParam.length()>10)
                fragmentParams.put("ParamValue",BarcodeParam.substring(0,10));//参数;
            else
                fragmentParams.put("ParamValue",BarcodeParam);//参数;
            mFragmentECallBack.FragmentEWorkAndTransParams(fragmentParams);
        } else Log.d("msg","mFragmentECallBack-----------空的咋办");

        try {
            queryJSON=new JSONArray("[]");
            //清除界面显示内容;
            clearFormText();
        } catch (JSONException e) {
            e.printStackTrace();
        }
        //执行SQL过程
        String SqlComm="Exec KeyPoint_SewOnBarcode @Barcode='" + BarcodeParam + "',@OrderNo='" + OrderNoParam + "',@StyleNo='" + StyleNoParam
                + "',@OPERTYPE='SCANBARCODE',@UserNo='"+curLoginUserNo+ "',@CPUID='"+CPUID+"'";
        //调用WebService过程并处理界面更新;
        ReadSQLData(SqlComm);
    }

    //清除界面显示内容
    private void clearFormText(){
        /*

         */
    }
    //填充界面显示内容;
    private void fillFormtext(){
        if (queryJSON.length()>0)
        {
            try {
                if (queryJSON.getJSONObject(0).has("StyleID")==true) curStyleID=queryJSON.getJSONObject(0).getString("StyleID");
                if (queryJSON.getJSONObject(0).has("HintInfo")==true) txt_HintInfo.setText(queryJSON.getJSONObject(0).getString("HintInfo"));
                if (queryJSON.getJSONObject(0).has("OrderNo")==true) txt_OrderNo.setText(queryJSON.getJSONObject(0).getString("OrderNo"));
                if (queryJSON.getJSONObject(0).has("StyleNo")==true) txt_StyleNo.setText(queryJSON.getJSONObject(0).getString("StyleNo"));
                if (queryJSON.getJSONObject(0).has("StyleSort")==true) txt_StyleSort.setText(queryJSON.getJSONObject(0).getString("StyleSort"));
                if (queryJSON.getJSONObject(0).has("PO")==true) txt_PO.setText(queryJSON.getJSONObject(0).getString("PO"));
                if (queryJSON.getJSONObject(0).has("Color")==true) txt_Color.setText(queryJSON.getJSONObject(0).getString("Color"));
                if (queryJSON.getJSONObject(0).has("PackNo")==true) txt_PackNo.setText(queryJSON.getJSONObject(0).getString("PackNo"));
                if (queryJSON.getJSONObject(0).has("Size")==true) txt_Size.setText(queryJSON.getJSONObject(0).getString("Size"));
                if (queryJSON.getJSONObject(0).has("ReadyScan")==true) txt_ReadyScan.setText(queryJSON.getJSONObject(0).getString("ReadyScan"));
                if (queryJSON.getJSONObject(0).has("OwenScan")==true) txt_OwenScan.setText(queryJSON.getJSONObject(0).getString("OwenScan"));
                if (queryJSON.getJSONObject(0).has("Number")==true) txt_Number.setText(queryJSON.getJSONObject(0).getString("Number"));
                if (queryJSON.getJSONObject(0).has("TargetNum")==true) txt_TargetNum.setText(queryJSON.getJSONObject(0).getString("TargetNum"));
                if (queryJSON.getJSONObject(0).has("TodaySewNum")==true) txt_TodaySewNum.setText(queryJSON.getJSONObject(0).getString("TodaySewNum"));
                if (queryJSON.getJSONObject(0).has("ErrInfo")==true)
                {
                    MediaPlayer mediaPlayer = MediaPlayer.create(getActivity(),R.raw.warn);
                    mediaPlayer.start();
                    AlertDialog alertDialog = new AlertDialog.Builder(getActivity())
                            .setTitle(getString(R.string.SystemHint)).setMessage(queryJSON.getJSONObject(0).getString("ErrInfo"))
                            .setPositiveButton(getString(R.string.Affirm), new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int which) {
                                    return;
                                }
                            }).create(); // 创建对话框
                    alertDialog.show(); // 显示对话框
                }
                if (queryJSON.getJSONObject(0).has("ImgFileName") == true){
                    curImageFileName =queryJSON.getJSONObject(0).getString("ImgFileName");
                    //判断本地是否有图片;
                    String imgfilepath = getActivity().getCacheDir().toString();
                    File file = new File(imgfilepath + "/" + curImageFileName);
                    System.out.println("图片文件路径:" + imgfilepath + "/" + curImageFileName);
                    //判断图片是否存在，如果不存在则从网络获取;
                    if (file.exists() == true) {
                        Log.d(TAG, "准备从本地取图片显示---------------");
                        //从本地取图片
                        Bitmap bitmap = getLoacalBitmap(imgfilepath + "/" + curImageFileName);
                        imgv_StlyleImage.setImageBitmap(bitmap);
                    } else {
                        Log.d(TAG, "发消息从网络获取图片---------------");
                        Drawable drawable = getResources().getDrawable(R.mipmap.err404);
                        BitmapDrawable errBitDraw = (BitmapDrawable) drawable;
                        imgv_StlyleImage.setImageBitmap(errBitDraw.getBitmap());
                        //发前消息，获取图片;
                        Message msg = new Message();
                        msg.what = msgGetImg;
                        fragmentHandler.removeMessages(msg.what);
                        fragmentHandler.sendMessage(msg);
                    }
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        System.out.println("fillFormtext----------edt_barcode置焦点");
        setEditBarcodeFocus();
    }
    // 隐藏手机键盘
    private void hideIM(View edt) {
        try {
            InputMethodManager im = (InputMethodManager) getActivity().getSystemService(Activity.INPUT_METHOD_SERVICE);
            IBinder windowToken = edt.getWindowToken();
            if (windowToken != null) {
                im.hideSoftInputFromWindow(windowToken, 0);
            }
        } catch (Exception e) {

        }
    }

    //设置焦点到扫描输入框
    private void setEditBarcodeFocus()
    {
        //设置焦点
        System.out.println(this.getClass().getName()+" 设置焦点-------------------------------1.Start");
        if (edt_barcode!=null) {
            edt_barcode.selectAll();
            edt_barcode.setFocusable(true);
            edt_barcode.setFocusableInTouchMode(true);
            edt_barcode.requestFocus();
            edt_barcode.requestFocusFromTouch();
            hideIM(getView());
            hideBottomUIMenu();
        }
        System.out.println(this.getClass().getName()+" 设置焦点-------------------------------1.End");
    }
    @Override
    public void onStart() {
        super.onStart();
        setEditBarcodeFocus();
    }

    @Override
    public void onClick(View v) {
        hideIM(v);
        switch (v.getId()){
            case R.id.btn_find:
                if (edt_barcode.getText().length()==0) {
                    curToast.setText(getString(R.string.PleaseInputBarcode));
                    curToast.show();
                } else searchBarcodeData(edt_barcode.getText().toString(),txt_OrderNo.getText().toString(),txt_StyleNo.getText().toString());
                break;
            case R.id.btn_Query:
                refreshDetailData("");
                break;
            case R.id.btn_editBarcode:
                edt_barcode.setInputType(InputType.TYPE_CLASS_TEXT);
                //1.得到InputMethodManager对象
                InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(getActivity().INPUT_METHOD_SERVICE);
                //2.调用showSoftInput方法显示软键盘，其中view为聚焦的view组件
                imm.showSoftInput(edt_barcode,InputMethodManager.SHOW_FORCED);
                break;
            case R.id.btn_Call:
                getPlaceList();
                break;
            default:
                break;
        }
    }

    private void getPlaceList()
    {
        System.out.println("getDepartment------------------------------------->");
        //执行SQL过程
        String SqlComm = "Exec KeyPoint_AGV_GetPlace @OPERTYPE='GETPLACE',@DepartNo='"+curDepartNo+"',@UserNo='"+curLoginUserNo+ "',@CPUID='"+CPUID+"'";
        ReadSQLData(SqlComm);
    }

    /**
     * 隐藏虚拟按键，并且全屏
     */
    protected void hideBottomUIMenu() {
        //隐藏状态栏和底部虚拟按键
        View decorView = getActivity().getWindow().getDecorView();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            int flag = View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                    | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY;
            decorView.setSystemUiVisibility(flag);
        }
    }
    //刷新今日扫描明细;
    private void refreshDetailData(String paramDate)
    {
        try {
            detailJSON=new JSONArray("[]");
            //显示到orderListGrid中;
            final DetailListAdapter detailListAdapter=new DetailListAdapter(getActivity());
            detailListView.setAdapter(detailListAdapter);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        //执行SQL过程
        String SqlComm="Exec KeyPoint_SewOnGetDetail @DepartmentNo='" + curDepartNo  + "',@WorkDate='"+paramDate
                + "',@OPERTYPE='DETAIL',@UserNo='"+curLoginUserNo+ "',@CPUID='" + CPUID +"'";
        //调用WebService过程并处理界面更新;
        ReadSQLData(SqlComm);

    }

    //直接连获取数据，与Handler配套使用;
    private void ReadSQLData(final String SQLComm) {
        Runnable run = new Runnable() {
            @Override
            public synchronized void run() {
                try{
                    reentrantLock.lock();
                    JSONArray jsonArray  = DBUtil.QuerySQL2JSON(SQLComm);
                    //往界面转数据;
                    if ((jsonArray!=null)&&(jsonArray.length()>0)) {
                        if (jsonArray.optJSONObject(0).has("OPERTYPE") == true) {
                            System.out.println("OPERTYPE:" + jsonArray.optJSONObject(0).getString("OPERTYPE"));
                            if (jsonArray.optJSONObject(0).getString("OPERTYPE").equals("SCANBARCODE")) {
                                queryJSON = jsonArray;
                                //刷新界面;
                                Message msg = new Message();
                                msg.what = MSG_SCANBARCODE;
                                fragmentHandler.removeMessages(msg.what);
                                fragmentHandler.sendMessage(msg);
                            }

                            if (jsonArray.optJSONObject(0).getString("OPERTYPE").equals("DETAIL"))
                            {
                                detailJSON=jsonArray;
                                //刷新界面;
                                Message msg = new Message();
                                msg.what = MSG_DETAIL;
                                fragmentHandler.removeMessages(msg.what);
                                fragmentHandler.sendMessage(msg);

                            }
                            if (jsonArray.optJSONObject(0).getString("OPERTYPE").equals("GETPLACE"))
                            {
                                placeJSON=jsonArray;
                                //刷新界面;
                                Message msg = new Message();
                                msg.what = MSG_GETPLACE;
                                fragmentHandler.removeMessages(msg.what);
                                fragmentHandler.sendMessage(msg);
                            }
                            if (jsonArray.optJSONObject(0).getString("OPERTYPE").equals("GETPATH"))
                            {
                                pathJSON=jsonArray;
                                //刷新界面;
                                Message msg = new Message();
                                msg.what = MSG_GETPATH;
                                fragmentHandler.removeMessages(msg.what);
                                fragmentHandler.sendMessage(msg);
                            }
                            if (jsonArray.optJSONObject(0).getString("OPERTYPE").equals("AGVREC"))
                            {
                                //刷新界面;
                                Message msg = new Message();
                                msg.what = MSG_AGVREC;
                                fragmentHandler.removeMessages(msg.what);
                                fragmentHandler.sendMessage(msg);
                            }

                        }
                        if (jsonArray.optJSONObject(0).has("PROCRESULT") == true) {
                            procRstJSON=jsonArray;
                            //刷新界面;
                            Message msg = new Message();
                            msg.what = MSG_PROCRESULT;
                            fragmentHandler.removeMessages(msg.what);
                            fragmentHandler.sendMessage(msg);
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    reentrantLock.unlock();
                }finally {
                    reentrantLock.unlock();
                }

            }

        };
        new Thread(run).start();
    }

    //刷新缸布列表;
    private void getImage(final String paramStyleID,final String paramStyleNo,final String paramStyleSort)
    {
        Runnable run = new Runnable() {
            @Override
            public void run() {
                try {
                    ResultSet re = DBUtil.OpenSQL("Exec KeyPoint_GetStylePNG @StyleID='" + paramStyleID + "',@StyleNo='" + paramStyleNo + "',@StyleSort='" + paramStyleSort + "'");
                    if (re != null) {
                        re.next();
                        //使用Blob对象接收数据库里的图片
                        if (re.findColumn("ImgResult") > -1) {
                            String ImgResult = re.getString("ImgResult");
                            if (ImgResult.equals("OK")) {
                                java.sql.Blob imgBlob = re.getBlob("ImgFile");
                                //获取Blob对象的二进制流;
                                InputStream imgInS = imgBlob.getBinaryStream();
                                //加载一个网络图片
                                Bitmap bitmap = BitmapFactory.decodeStream(imgInS);
                                //保存图片;
                                saveBitmap(bitmap, curImageFileName);
                                //发消息显示图片;
                                Message msg = new Message();
                                msg.what = msgShowImage;
                                fragmentHandler.removeMessages(msg.what);
                                fragmentHandler.sendMessage(msg);
                            }
                        }
                    }
                    re.getStatement().getConnection().close();
                } catch (SQLException e) {
                    e.printStackTrace();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };
        new Thread(run).start();
    }


    /**
     * 删除方法 这里只会删除某个文件夹下的文件，如果传入的directory是个文件，将不做处理 * * @param directory
     */
    private static void deleteFilesByDirectory(File directory) {
        if (directory != null && directory.exists() && directory.isDirectory()) {
            for (File item : directory.listFiles()) {
                item.delete();
            }
        }
    }

    /**
     * @param @param  url 本地路径
     * @param @return
     * @return Bitmap
     * @throws
     * @Title: getLoacalBitmap
     * @Description: 加载本地图片
     */
    public Bitmap getLoacalBitmap(String url) {
        if (url != null) {
            FileInputStream fis = null;
            try {
                fis = new FileInputStream(url);
                return BitmapFactory.decodeStream(fis); // /把流转化为Bitmap图片
            } catch (FileNotFoundException e) {
                e.printStackTrace();
                return null;
            } finally {
                if (fis != null) {
                    try {
                        fis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    fis = null;
                }
            }
        } else {
            return null;
        }
    }


    /**
     * 保存文件
     */
    public void saveBitmap(Bitmap bm, String fileName) {
        //获取MainActivity
        MainActivity activity = (MainActivity) getActivity();
        //String imgfilepath=activity.SaveFilePath+activity.SaveIMGFolder;
        String imgfilepath = activity.getCacheDir().toString();
        Log.d("saveBitmap", "imgfilepath:" + imgfilepath);
        File f = new File(imgfilepath, fileName);
        if (f.exists()) {
            f.delete();
        }
        try {
            FileOutputStream out = new FileOutputStream(f);
            if (fileName.toUpperCase().indexOf("PNG") > 0)
                bm.compress(Bitmap.CompressFormat.PNG, 90, out);
            if ((fileName.toUpperCase().indexOf("JPG") > 0) || (fileName.toUpperCase().indexOf("JPEG") > 0))
                bm.compress(Bitmap.CompressFormat.JPEG, 90, out);
            out.flush();
            out.close();
            Log.i("saveBitmap", "已经保存成功");
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

    //订单表格适配器;
    public final class DetailListAdapter extends BaseAdapter {
        private LayoutInflater inflater;
        public DetailListAdapter(Context context) {
            inflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }
        @Override
        public int getCount() {
            return detailJSON.length();
        }

        @Override
        public Object getItem(int position) {
            try {
                return detailJSON.get(position);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) convertView = inflater.inflate(R.layout.fragment_e_listhead, null, false);
            int pullVatListWidth=parent.getWidth();
            convertView.setLayoutParams(new ListView.LayoutParams((int)pullVatListWidth,(int)(38)));
            int color = getResources().getColor(R.color.text_black);
            String tmpValue;
            try {
                Log.d("msg","getView()----------------------------------------------------->"+position);
                if (detailJSON.optJSONObject(position).has("ConColor")==true) {
                    tmpValue = detailJSON.optJSONObject(position).getString("ConColor").toString();
                    if (tmpValue.equals("1"))
                        color = getResources().getColor(R.color.text_blue);
                    if (tmpValue.equals("2"))
                        color = getResources().getColor(R.color.text_red);
                    if (tmpValue.equals("3"))
                        color = getResources().getColor(R.color.text_gray);
                    if (tmpValue.equals("0"))
                        color = getResources().getColor(R.color.text_black);
                }
                TextView tv = (TextView) convertView.findViewById(R.id.txt_item_hoursection);// 显示文字
                if (detailJSON.optJSONObject(position).has("HourSection")==true)
                    tv.setText(detailJSON.optJSONObject(position).get("HourSection").toString());
                tv.setTextColor(color);
                tv = (TextView) convertView.findViewById(R.id.txt_item_orderno);// 显示文字
                if (detailJSON.optJSONObject(position).has("OrderNo")==true)
                    tv.setText(detailJSON.optJSONObject(position).get("OrderNo").toString());
                tv.setTextColor(color);
                tv = (TextView) convertView.findViewById(R.id.txt_item_styleno);// 显示文字
                if (detailJSON.optJSONObject(position).has("StyleNo")==true)
                    tv.setText(detailJSON.optJSONObject(position).get("StyleNo").toString());
                tv.setTextColor(color);
                tv = (TextView) convertView.findViewById(R.id.txt_item_stylesort);// 显示文字
                if (detailJSON.optJSONObject(position).has("StyleSort")==true)
                    tv.setText(detailJSON.optJSONObject(position).get("StyleSort").toString());
                tv.setTextColor(color);
                tv = (TextView) convertView.findViewById(R.id.txt_item_color);// 显示文字
                if (detailJSON.optJSONObject(position).has("Color")==true)
                    tv.setText(detailJSON.optJSONObject(position).get("Color").toString());
                tv.setTextColor(color);
                tv = (TextView) convertView.findViewById(R.id.txt_item_size);// 显示文字
                if (detailJSON.optJSONObject(position).has("Size")==true)
                    tv.setText(detailJSON.optJSONObject(position).get("Size").toString());
                tv.setTextColor(color);
                tv = (TextView) convertView.findViewById(R.id.txt_item_number);// 显示文字
                if (detailJSON.optJSONObject(position).has("Number")==true)
                    tv.setText(detailJSON.optJSONObject(position).get("Number").toString());
                tv.setTextColor(color);


            } catch (JSONException e) {
                e.printStackTrace();
                System.out.println(e.getMessage());
            }
            Log.d("msg","DetailGridAdapter_position:"+position);
            return convertView;
        }
    }


}
